package com.gamotech.communication.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.gamotech.communication.connect.IBaseAction
import com.gamotech.communication.connect.impl.UdpService
import com.gamotech.communication.utils.UrlContract
import java.net.InetAddress
import java.util.*

// 后台监听服务
class MessageListenService : Service() {
    var action: IBaseAction? = null

    private var messageUdpServer: UdpService? = null
    private var beatHeartUdpServer: UdpService? = null
    private val beatHeartTimer = Timer()
    private val beatHeartTask = object : TimerTask() {
        override fun run() {
            beatHeartUdpServer?.sendUdpMessage(
                UrlContract.serverBaseAddress,
                UrlContract.serverBeatHeartPort,
                "1",
                null,
                null
            )
        }
    }

    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        messageUdpServer = UdpService.getInstance()
        messageUdpServer?.init(UrlContract.appMessagePort) // 监听本地端口

        beatHeartUdpServer = UdpService.getInstance()
        beatHeartUdpServer?.init(UrlContract.appBeatHeartPort) // 监听心跳回调
        beatHeartUdpServer?.action = object : IBaseAction {
            override fun receiveMessage(msg: String, address: InetAddress, port: Int) {
                action?.receiveMessage(msg, address, port)
            }

            override fun onError(msg: String) {
                action?.onError(msg)
            }
        }

        beatHeartTimer.scheduleAtFixedRate(beatHeartTask, 1000, 1000)
    }

    fun sendMessage(msg: String, sourceAccount: String, targetAccount: String) {
        messageUdpServer?.sendUdpMessage(
            UrlContract.serverBaseAddress,
            UrlContract.serverMessagePort,
            msg,
            sourceAccount, targetAccount
        )
    }

    override fun onDestroy() {
        super.onDestroy()
        messageUdpServer?.dispose()
        beatHeartTimer.cancel()
    }
}